package com.ddx.service.impl;

import com.ddx.common.enums.ErrorCode;
import com.ddx.common.enums.OrderStatus;
import com.ddx.common.exception.BusinessException;
import com.ddx.common.util.DateUtil;
import com.ddx.dao.*;
import com.ddx.dto.ShoppingOrderDetailVo;
import com.ddx.dto.ShoppingOrderVo;
import com.ddx.pojo.*;
import com.ddx.service.IShoppingUserCenterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2018/8/31
 */
@Service
public class ShoppingUserCenterServiceImpl implements IShoppingUserCenterService {
    private static Logger logger = LoggerFactory.getLogger(ShoppingUserCenterServiceImpl.class);
    @Autowired
    ShoppingAccountMapper shoppingAccountMapper;
    @Autowired
    ShoppingUserAddressMapper shoppingUserAddressMapper;
    @Autowired
    ShoppingOrderMapper shoppingOrderMapper;
    @Autowired
    ShoppingOrderDetailMapper shoppingOrderDetailMapper;
    @Autowired
    ShoppingStoreMapper shoppingStoreMapper;
    @Autowired
    ShoppingProductMapper shoppingProductMapper;
    @Autowired
    ShoppingSpecMapper shoppingSpecMapper;
    @Autowired
    ShoppingAccountFlowMapper shoppingAccountFlowMapper;
    @Autowired
    UserMapper userMapper;
    @Value("${image_address}")
    String imageAddress;



    /**
     * 用户收货地址
     * @param userId
     * @return
     */
    @Override
    public List<ShoppingUserAddress> addressInfo(String userId) {
        logger.info("用户收货地址入参userId={}",userId);
        List<ShoppingUserAddress> list=shoppingUserAddressMapper.selectAdressByUserId(userId);
        return list;
    }
    /**
     * 用户订单
     * @param shoppingUserVo
     * @return
     */
    @Override
    public List<ShoppingOrderVo> orderInfo(ShoppingOrderVo shoppingUserVo) {
        logger.info("用户订单入参shoppingUserVo={}",shoppingUserVo);
        //查询所有订单
        List<ShoppingOrder> shoppingOrder=shoppingOrderMapper.selectOrderByUserId(shoppingUserVo);
        List<ShoppingOrderVo> voList=new ArrayList<>();
        for(ShoppingOrder order:shoppingOrder) {
            ShoppingOrderVo vo=new ShoppingOrderVo();
            //查询店铺信息
            ShoppingStore shoppingStore=shoppingStoreMapper.selectByPrimaryKey(Integer.parseInt(order.getShopId()));
            vo.setStoreName(shoppingStore.getName());
            vo.setStatusDes(OrderStatus.getOrderStatus(order.getStatus()).getDesc());
            vo.setCount(order.getCount());
            vo.setAmount(order.getAmount());
            vo.setFee(order.getFee());
            List<ShoppingOrderDetail> details = shoppingOrderDetailMapper.selectOrderDetailByOrderId(order.getOrderId());
            List<ShoppingOrderDetailVo> detailVos=new ArrayList<>();
            for(ShoppingOrderDetail detail:details){
                //查询商品信息
                ShoppingProduct shoppingProduct =shoppingProductMapper.selectByPrimaryKey(Integer.parseInt(detail.getProductId()));
                ShoppingSpec shoppingSpec=shoppingSpecMapper.selectByPrimaryKey(Integer.parseInt(detail.getSpecId()));
                ShoppingOrderDetailVo detailVo=new ShoppingOrderDetailVo();
                detailVo.setProductName(detail.getProductName());
                detailVo.setPrice(detail.getPrice());
                detailVo.setSpecinfo(shoppingSpec.getSpecJson());
                detailVo.setPicture(imageAddress+shoppingProduct.getPicture());
                detailVos.add(detailVo);
            }
            vo.setStatus(order.getStatus());
            vo.setDetailVos(detailVos);
            vo.setOrderId(order.getOrderId());
            voList.add(vo);
        }
        return voList;
    }

    /**
     * 添加地址
     * @param address
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public void saveAddress(ShoppingUserAddress address) {
        if(address.getIsdefault()==1){
            //先将用户之前默认收货地址修改为非默认收货地址
            shoppingUserAddressMapper.updateUserDefault(address.getUserId());
        }
        shoppingUserAddressMapper.insertSelective(address);

    }

    /**
     * 删除地址
     * @param id
     * @return
     */
    @Override
    public void delAddress(Long id,String userId) {
        logger.info("删除地址入参id={},userId={}",id,userId);
        //先查询地址是不是登录的这个用户
        ShoppingUserAddress record=new ShoppingUserAddress();
        record.setUserId(userId);
        record.setId(id);
        List<ShoppingUserAddress> list=shoppingUserAddressMapper.selectByRecord(record);
        if(list==null||list.size()==0){
           throw new BusinessException(ErrorCode.BUSSINESS_ERROR_213);
        }
        shoppingUserAddressMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改地址
     * @param address
     * @return
     */

    @Override
    public void updateAddress(ShoppingUserAddress address) {
        shoppingUserAddressMapper.updateByPrimaryKeySelective(address);

    }


    /**
     * 设为默认
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void defaultAddress(Long addressId,String userId) {
        //先将用户之前默认收货地址修改为非默认收货地址
        shoppingUserAddressMapper.updateUserDefault(userId);
        //将这个地址设为默认
        shoppingUserAddressMapper.updateDefaultByUserId(addressId);
    }

    @Override
    public ShoppingUserAddress getDefaultAddress(String userId) {
        return shoppingUserAddressMapper.getDefaultAddress(userId);
    }

    @Override
    public ShoppingUserAddress getAddressInfo(String addressId) {
        return shoppingUserAddressMapper.selectByPrimaryKey(Long.parseLong(addressId));
    }

    @Override
    public Map<String, Object> myAccount(String userId) {
        Map<String,Object> map=new HashMap<>();
        ShoppingAccount shoppingAccount=shoppingAccountMapper.selectAccountByUserId(userId);
        map.put("amount",shoppingAccount.getTotalAmount()==null?BigDecimal.ZERO:shoppingAccount.getTotalAmount());
        ShoppingStore shoppingStore=shoppingStoreMapper.selectByUserId(Integer.parseInt(userId));
        if(shoppingStore==null){
            map.put("isHaveStore",0);
        }else{
            map.put("isHaveStore",1);
        }
        User user=userMapper.selectByPrimaryKey(Integer.parseInt(userId));
        map.put("totalPoint",user.getTotalPoint());
        map.put("isBond",user.getIsBond());
        map.put("bond",600);
        return map;
    }
}
